﻿#region Copyright ©2008-2011, Technische Universitaet Muenchen
// ====================================================================================================
//
// Last Changed by       $Author: then $
// Last Changed Date     $LastChangedDate: 2009-04-01 10:10:55 +0200 (Wed, 01 Apr 2009) $
// Last Changed Revision $Rev: 49 $
//
// ====================================================================================================
#endregion

using System.IO;
using System.Windows;
using System.Windows.Media;
using Microsoft.Win32;
using System.Linq;
using Tum.CollabXT.VModellXT.Properties;
using System;
using Tum.CollabXT.VModellXT.Tailoring;
using System.Windows.Forms;

namespace Tum.CollabXT.VModellXT
{
    /// <summary>
    /// Interaction logic for VModellTailoringPage.xaml
    /// </summary>
    public partial class VModellTailoringPage : VModellPage
    {
        VModellXTProcessProvider _ProcessProvider;
        IConversionWorkflow _ConversionWorkflow;


        public VModellTailoringPage()
        {
            InitializeComponent();
        }

        internal override void ReceiveHandles(VModellConfigFrame configFrame, VModellXTProcessProvider processProvider, IConversionWorkflow conversionWorkflow, bool advance)
        {
            _ProcessProvider = processProvider as VModellXTProcessProvider;
            if (_ProcessProvider == null)
                throw new ArgumentNullException("processProvider");

            if(string.IsNullOrEmpty(_ProcessProvider.VModellFile))
                throw new ArgumentException("processProvider.VModellFile is not set");


            _ConversionWorkflow = conversionWorkflow;

            //Skip this page, if no internal tailoring is used
            if (!_ProcessProvider.UseInternalTailoring)
            {
                configFrame.ChangePage(advance);
                return;
            }

            string modelDocumentFolder = Path.GetDirectoryName(_ProcessProvider.VModellFile);

            //Initialize tailoring structure
            if (_ProcessProvider.InternalTailoring != null)
            {
                //Check if the model file this tailoring was initialized with is still used
                if (!(new FileInfo(_ProcessProvider.InternalTailoring.Model.ModelDocumentPath)).FullName
                      .Equals((new FileInfo(_ProcessProvider.VModellFile).FullName)))
                {
                    //It is not -> reset tailoring
                    _ProcessProvider.InternalTailoring = null;
                }
            }
            if(_ProcessProvider.InternalTailoring == null)
            {
                //Initialize tailoring
                _ProcessProvider.InternalTailoring = new TailoringBuilder(new Tailoring.VModellXT(modelDocumentFolder));
            }

            InitializeUiFromData();
        }

        private void InitializeUiFromData()
        {
            //Disable elements not yet necessary
            comboBoxProjectTypeVariant.IsEnabled = false;
            listBoxCharacteristics.IsEnabled = false;

            //Initialize project type list
            comboBoxProjectType.ItemsSource = _ProcessProvider.InternalTailoring.Model.ProjectTypes;
            if (_ProcessProvider.InternalTailoring.ProjType != null)
                comboBoxProjectType.SelectedItem = _ProcessProvider.InternalTailoring.ProjType;

            //Initialize project type variant list
            if (_ProcessProvider.InternalTailoring.ProjTypeVariant != null)
                comboBoxProjectTypeVariant.SelectedItem = _ProcessProvider.InternalTailoring.ProjTypeVariant;

            //Set project name
            textBoxProjectName.Text = _ProcessProvider.InternalTailoring.ProjName;

            //Save tailored model settings
            checkBoxSaveTailoredModel.IsChecked = _ProcessProvider.SaveInternalTailoringModel;
            labelSaveModelPathValue.Content = _ProcessProvider.SaveInternalTailoringModelPath;

            CheckBoxSaveTailoredModel_Checked(null, null);

            //Button states
            UpdateWorkflowButtons();
        }

        private void SaveUiSettingsToData()
        {
            if (_ProcessProvider.UseInternalTailoring)
            {
                _ProcessProvider.InternalTailoring.ProjName = textBoxProjectName.Text;
                _ProcessProvider.InternalTailoring.ProjType = comboBoxProjectType.SelectedItem as ProjectType;
                _ProcessProvider.InternalTailoring.ProjTypeVariant = comboBoxProjectTypeVariant.SelectedItem as ProjectTypeVariant;

                _ProcessProvider.InternalTailoring.ProjCharacteristics.Clear();
                foreach (var curProjChar in _ProcessProvider.InternalTailoring.ProjType.ProjectCharacteristics.Union(_ProcessProvider.InternalTailoring.ProjTypeVariant.ProjectCharacteristics))
                {
                    _ProcessProvider.InternalTailoring.ProjCharacteristics.Add(curProjChar, curProjChar.DefaultValue);
                }

                _ProcessProvider.SaveInternalTailoringModel = checkBoxSaveTailoredModel.IsChecked.Value;
                _ProcessProvider.SaveInternalTailoringModelPath = labelSaveModelPathValue.Content as string;
            }
        }

        private void UpdateWorkflowButtons()
        {
            if(_ProcessProvider != null)
            {
                _ConversionWorkflow.UpdateButtonState(true,
                                                      comboBoxProjectType.SelectedItem != null
                                                   && comboBoxProjectTypeVariant.SelectedItem != null
                                                   && (!checkBoxSaveTailoredModel.IsChecked.Value
                                                       || !string.IsNullOrEmpty(labelSaveModelPathValue.Content as string)));
            }
        }

        internal override bool ChangePage(bool advance)
        {
            SaveUiSettingsToData();
            return true;
        }

        private void comboBoxProjectType_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            listBoxCharacteristics.ItemsSource = null;

            var selectedProjType = comboBoxProjectType.SelectedItem as ProjectType;
            if (selectedProjType == null)
                return;

            comboBoxProjectTypeVariant.IsEnabled = true;
            listBoxCharacteristics.IsEnabled = false;

            //Initialize project type variant list
            comboBoxProjectTypeVariant.ItemsSource = selectedProjType.ProjectTypeVariants;

            UpdateWorkflowButtons();
        }

        private void comboBoxProjectTypeVariant_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            listBoxCharacteristics.ItemsSource = null;

            var selectedProjType = comboBoxProjectType.SelectedItem as ProjectType;
            if (selectedProjType == null)
                return;

            var selectedProjTypeVar = comboBoxProjectTypeVariant.SelectedItem as ProjectTypeVariant;
            if (selectedProjTypeVar == null)
                return;

            listBoxCharacteristics.IsEnabled = true;

            //Initialize project characteristics list
            listBoxCharacteristics.ItemsSource = selectedProjType.ProjectCharacteristics.Union(selectedProjTypeVar.ProjectCharacteristics);

            UpdateWorkflowButtons();
        }

        private void CheckBoxSaveTailoredModel_Checked(object sender, RoutedEventArgs e)
        {
            if (checkBoxSaveTailoredModel.IsChecked.Value)
            {
                labelSaveModelPath.Foreground = string.IsNullOrEmpty(labelSaveModelPathValue.Content as string) ? Brushes.Red : Brushes.Black;
                labelSaveModelPathValue.Foreground = Brushes.Black;
                buttonSetSaveModelPath.IsEnabled = true;
            }
            else
            {
                labelSaveModelPath.Foreground = labelSaveModelPathValue.Foreground = Brushes.Gray;
                buttonSetSaveModelPath.IsEnabled = false;
            }
            UpdateWorkflowButtons();
        }

        private void buttonSetSaveModelPath_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog()
            {
                ShowNewFolderButton = true
            };
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                labelSaveModelPathValue.Content = fbd.SelectedPath;
                CheckBoxSaveTailoredModel_Checked(null, null);
            }
            UpdateWorkflowButtons();
        }
    }
}
